<?php
/**
 * $Author: BEESSHOP $
 * ============================================================================
 * ============================================================================
 */
namespace app\module\controllers;

use app\models\CouponRecorder;
use app\models\CouponuserRecorder;
use app\models\GoodsRecorder;
use app\models\MessageRecorder;
use app\models\NewRecorder;
use app\models\NewuserRecorder;
use app\models\OrderRecorder;
use app\models\PaytypeRecorder;
use app\models\PstypeRecorder;
use app\models\PurchaseRecorder;
use app\models\YxnumRecorder;

class OrderController extends BaseController{

    public function beforeAction($action)
    {
        if(!$this->check_login()){
            $result = ['result'=>'login_error','data'=>'请先登录'];
            echo json_encode($result);
            return false;
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }


    public function actionOrder(){
        $id = \Yii::$app->request->post('id');
        $model = OrderRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关订单，请重新操作或联系客服处理'];
            return json_encode($result);
        }
        $arr=[];
        $res = json_decode($model->order_content,true);
        $list = $res;
        $total_price=$model->total_price;
        $hd_price = json_decode($model->hd_price,true);
        $arr['order_name'] = $model->order_name;
        $arr['addtime'] = date('Y-m-d H:i:s',$model->addtime);
        $arr['id'] = $model->id;
        $arr['is_pay'] = $model->is_pay;
        $arr['address'] = json_decode($model->address,true);
        $arr['yhq_name'] = "";
        if($model->is_pay){
            //获取优惠券
            $arr['yhq_name'] = empty($model->coupon_id)?"未使用优惠券":"查看优惠券";
        }
        $arr['coupon_id'] = $model->coupon_id;
        $order_else = json_decode($model->order_else,true);
        //获取订阅信息ID
        $message = MessageRecorder::find()->where('message_cate=1')->one();
        $arr['message_id'] = ($message)?$message->message_id:'';
        $result = ['result'=>1,'data'=>$arr,'list'=>$list,'total_price'=>$total_price,'hd_price'=>$hd_price,'order_else'=>$order_else];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }

    public function actionPaytypelist(){
        $list = PaytypeRecorder::find()->select(['id','pay_type','pay_name'])->where('is_pay=1')->asArray()->all();
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }


    public function actionOrderpay(){
        $post = \Yii::$app->request->post('form');
        $id = intval($post['id']);
        $pay_type = intval($post['pay_type']);
        $coupon_id = intval($post['coupon_id']);
        $ps_type = intval($post['ps_type']);
        $ps_type = empty($ps_type)?1:$ps_type;
        if(empty($pay_type)){
            $result =['result'=>0,'data'=>'先选择支付方式'];
            return json_encode($result);
        }
        $model = OrderRecorder::find()->where('id='.$id)->andWhere('user_id='.$this->user->id)->andWhere('status=0')->one();



        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关订单，可能已取消订单，请重新操作'];
            return json_encode($result);
        }
        if($model->is_pay){
            $result = ['result'=>0,'data'=>'订单已经支付，请不要重复支付'];
            return json_encode($result);
        }

        $yx = empty($model->yx)?[]:json_decode($model->yx,true);

        //判断限制购买数量商品
        $hd_id_arr = json_decode($model->purchase_arr,true);
        $hd_num_arr = json_decode($model->purchase_user_num_arr,true);
        if(count($hd_id_arr)>0){
            foreach($hd_id_arr as $k=>$v){
                if($hd_num_arr[$k]<0){
                    continue;
                }

                $hd_model = PurchaseRecorder::find()->where('id='.$v)->andWhere('status=0')->one();
                if(empty($hd_model)){
                    $result = ['result'=>0,'data'=>'支付失败，限时购活动已取消'];
                    return json_encode($result);
                }
                if($hd_model->endtime<time()){
                    $result = ['result'=>0,'data'=>'支付失败，限时购活动已结束'];
                    return json_encode($result);
                }
                $s_model = NewuserRecorder::find()->where('user_id='.$this->user->id)->andWhere('hd_id='.$v)->andWhere('hd_type=1')->one();
                if($s_model){
                    $s_model->num = ($s_model->num>$hd_num_arr[$k])?$s_model->num:$hd_num_arr[$k];
                    if($s_model->num>$hd_model->g_limit){
                        $result = ['result'=>0,'data'=>'支付失败，限时购已经达到最大购买数量，请取消订单'];
                        return json_encode($result);
                    }
                }

            }
        }

        $hd_id_arr = json_decode($model->new_user_arr,true);
        $hd_num_arr = json_decode($model->new_user_num_arr,true);
        if(count($hd_id_arr)>0){
            foreach($hd_id_arr as $k=>$v){
                if($hd_num_arr[$k]<0){
                    continue;
                }

                $hd_model = NewRecorder::find()->where('id='.$v)->andWhere('status=0')->one();
                if(empty($hd_model)){
                    $result = ['result'=>0,'data'=>'支付失败，新人购活动已取消'];
                    return json_encode($result);
                }
                $s_model = NewuserRecorder::find()->where('user_id='.$this->user->id)->andWhere('hd_id='.$v)->andWhere('hd_type=0')->one();
                if($s_model){
                    $s_model->num = ($s_model->num>$hd_num_arr[$k])?$s_model->num:$hd_num_arr[$k];
                    if($s_model->num>$hd_model->g_limit){
                        $result = ['result'=>0,'data'=>'支付失败，本次新人购活动已经达到最大购买数量，【限购：'.$hd_model->g_limit.'件】请取消订单'];
                        return json_encode($result);
                    }
                }

            }
        }


        if($coupon_id){
            $user_coupon_model = CouponuserRecorder::find()->where('id=:id',[':id' => $coupon_id])->andWhere('user_id='.$this->user->id)
                ->andWhere('is_use=0')->andWhere('is_del=0')->one();
            if($user_coupon_model){
                $coupon_model = CouponRecorder::find()->where('id='.$user_coupon_model->coupon_id)->one();
               if($coupon_model->status==1){
                   $result = ['result'=>0,'data'=>'优惠券活动已经结束,请移除'];
                   return json_encode($result);
               }
               //判断是否在使用期间
                if(time()>strtotime("+ ".$coupon_model->day." days",$user_coupon_model->addtime)){
                    $result = ['result'=>0,'data'=>'优惠券已过期，请移除'];
                    return json_encode($result);
                }

                if($model->total_price<$coupon_model->count){
                    $result = ['result'=>0,'data'=>'消费总金额不足，不能使用当前优惠券，请更换或移除'];
                    return json_encode($result);
                }
                $price = $model->total_price-$coupon_model->reduce;
                $model->total_price = $price;
                //记录参与的活动
                $yx_arr['type'] = 3;
                $yx_arr['id'] = $coupon_model->id;
                $yx[]=$yx_arr;
            }
        }

        //运费设置
        $psmodel = PstypeRecorder::find()->where('ps_type=:type',[':type' => $ps_type])->one();
        if(!empty($psmodel)){
            $model->total_price+=$psmodel->ps_price;
        }

        $result =['result'=>0,'data'=>'支付失败，请重新操作或联系客服处理'];
        $is_pay=0;
        switch($pay_type){
            case 1://微信支付
                $pay_body=[
                  "appid"=>\Yii::$app->params['appid'],
                  "mch_id"=>\Yii::$app->params['sh_id'],
                    "nonce_str"=>\Yii::$app->security->generateRandomString(),
                    "sign_type"=>"MD5",
                    "out_trade_no"=>$model->order_name,
                    "fee_type"=>'CNY',
                    "total_fee"=>intval($model->total_price*100),
                    "notify_url"=>"https://www.weixin.qq.com/wxpay/pay.php",
                    "trade_type"=>"JSAPI",
                    "openid"=>$this->user->openid,
                    "body"=>\Yii::$app->params['web_name']."订单支付",
                ];

                $res=$this->wxpay($pay_body);
                $reply['yx'] = $yx;
                $reply['coupon_id'] = $coupon_id;
                $reply['order_id'] = $model->id;
                $result = ['result'=>1,'data'=>$res,"pay_type"=>$pay_type,"reply"=>$reply];
                $is_pay=1;
                break;
            case 2://余额支付
                if($this->user->pay_num<$model->total_price){
                    $result = ['result'=>0,'data'=>'余额不足，请充值'];
                    return json_encode($result);
                }
                $this->user->pay_num = number_format($this->user->pay_num-$model->total_price,"2",".","");
                $this->user->total_num+=$model->total_price;

                $sql = \Yii::$app->db->beginTransaction();
                try{

                    $this->user->save(false);

                    $this->change_pay_info($model->purchase_arr, $model->purchase_user_num_arr, 1);
                    $this->change_pay_info($model->new_user_arr, $model->new_user_num_arr);
                    //减库存
                    $this->goods_num_reduce($model->goods_attr);
                    //记录日志
                    $this->pay_log($this->user->id, 1, "购买商品", $model->total_price, $model->id);





                    if ($user_coupon_model) {
                        $user_coupon_model->is_use = 1;
                        $user_coupon_model->order_id = $model->id;
                        $user_coupon_model->save(false);
                        $model->coupon_id = $user_coupon_model->id;
                    }

                    foreach ($yx as $v) {
                        $yx_model = new YxnumRecorder();
                        $yx_model->user_id = $this->user->id;
                        $yx_model->yx_id = $v['id'];
                        $yx_model->yx_type = $v['type'];
                        $yx_model->addtime = time();
                        $yx_model->is_pay = 1;
                        $yx_model->save(false);
                    }
                    $model->is_pay = 1;

//                    $model->save(false);
                    $sql->commit();
                    $result = ['result' => 1, 'data' => '支付成功', "pay_type" => $pay_type];
                    $is_pay=1;
                }catch (\Exception $e){
                    $sql->rollBack();
                    $result = ['result'=>0,'data'=>'支付失败，请重新操作'];
                }


                break;
            case 3://yhk
                $result = ['result' => 1, 'data' => '等待支付', "pay_type" => $pay_type,'code_num'=>$model->code_num];
                break;
            case 4://sm
                $result = ['result' => 1, 'data' => '等待支付', "pay_type" => $pay_type,'code_num'=>$model->code_num];
                break;
            default:
                $result = ['result'=>0,'data'=>'请选择支付方式'];
                break;
        }
        $model->pay_type=$pay_type;
        $model->ps_type = $ps_type;
        $model->save(false);
        if($is_pay){
            $this->dyj($model);
        }

        return json_encode($result);

    }

    public function actionPayyhkinfo(){
        $id = \Yii::$app->request->post('id');
        $model = OrderRecorder::find()->select(['id','order_name','total_price','code_num'])->where('id=:id',[':id' => $id])
            ->andWhere('pay_type=3')->asArray()->one();
        if(empty($model)){
            $result = ['result'=>0,'data'=>'不存在相关订单，亲重新操作'];
            return json_encode($result,JSON_NUMERIC_CHECK);
        }
        $pay = PaytypeRecorder::find()->select(['pay_content','pay_info'])->where('pay_type=3')->one();
        if(!empty($pay)){
            $model['pay_info'] = $pay->pay_info;
            $pay_content = json_decode($pay->pay_content,true);
            $model['yhk'] = $pay_content['yhk'];
            $model['yhk_name'] = $pay_content['yhk_name'];
            $model['yhk_num'] = $pay_content['yhk_num'];
        }
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }

    public function actionPaysminfo(){
        $id = \Yii::$app->request->post('id');
        $model = OrderRecorder::find()->select(['id','order_name','total_price','code_num'])->where('id=:id',[':id' => $id])
            ->andWhere('pay_type=4')->asArray()->one();
        if(empty($model)){
            $result = ['result'=>0,'data'=>'不存在相关订单，亲重新操作'];
            return json_encode($result,JSON_NUMERIC_CHECK);
        }
        $pay = PaytypeRecorder::find()->select(['pay_content','pay_info'])->where('pay_type=4')->one();
        if(!empty($pay)){
            $model['pay_info'] = $pay->pay_info;
            $pay_content = json_decode($pay->pay_content,true);
            $model['pic'] = $pay_content['pic'];

        }
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }

    public function actionPstypelist(){
        $list = PstypeRecorder::find()->where('is_type=1')->select(['id','ps_type','ps_name','content','ps_price'])->asArray()->all();
        $result  =['result'=>1,"data"=>$list];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }


    public function actionWxpay(){
        $post = \Yii::$app->request->post('reply');
        $order_model = OrderRecorder::find()->where('id=:id',[':id' => $post['order_id']])->one();
        $user_coupon_model = CouponuserRecorder::find()->where('id=:id',[':id' => $post['coupon_id']])->andWhere('user_id='.$this->user->id)
            ->andWhere('is_use=0')->andWhere('is_del=0')->one();
        if(empty($order_model)){
            $result = ['result'=>0,'data'=>'不存在相关订单，如果已经支付，请联系客服处理'];
            return json_encode($result);
        }
        $body=[
            "appid"=>\Yii::$app->params['appid'],
            "mch_id"=>\Yii::$app->params['sh_id'],
            "out_trade_no"=>$order_model->order_name,
            "nonce_str"=>\Yii::$app->security->generateRandomString(),
        ];
        ksort($body);
        $sign="";
        $xml="<xml>";
        foreach($body as $k=>$v){
            $xml.="<{$k}>{$v}</{$k}>";
            $sign.="{$k}={$v}&";
        }
        $sign.="key=".\Yii::$app->params['sh_key'];
        $sign = strtoupper(md5($sign));
        $xml.="<sign>{$sign}</sign></xml>";
        $url = "https://api.mch.weixin.qq.com/pay/orderquery";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $res = curl_exec($ch);
        curl_close($ch);
        $res = simplexml_load_string($res,"SimpleXMLElement",LIBXML_NOCDATA);
        $res = json_decode(json_encode($res),true);
        if($res['trade_state']=="SUCCESS"){//支付成功
            $sql = \Yii::$app->db->beginTransaction();
            try{
                $this->user->total_num+=$order_model->total_price;//总消费金额
                $this->user->save(false);
                $this->change_pay_info($order_model->purchase_arr,$order_model->purchase_user_num_arr,1);
                $this->change_pay_info($order_model->new_user_arr,$order_model->new_user_num_arr);
                //减库存
                $this->goods_num_reduce($order_model->goods_attr);
                //记录日志
                $this->pay_log($this->user->id,2,"购买商品",$order_model->total_price,$order_model->id);


                if($user_coupon_model){
                    $user_coupon_model->is_use=1;
                    $user_coupon_model->order_id=$order_model->id;
                    $user_coupon_model->save(false);
                    $order_model->coupon_id=$user_coupon_model->id;
                }

                foreach($post['yx'] as $v){
                    $yx_model = new YxnumRecorder();
                    $yx_model->user_id = $this->user->id;
                    $yx_model->yx_id=$v['id'];
                    $yx_model->yx_type=$v['type'];
                    $yx_model->addtime = time();
                    $yx_model->is_pay=1;
                    $yx_model->save(false);
                }
                $order_model->is_pay = 1;
                $order_model->save(false);
                $sql->commit();
                $result = ['result'=>1,'data'=>'支付成功'];
            }catch (\Exception $e){
                $sql->rollBack();
                $result = ['result'=>0,'data'=>'支付出现错误，请联系客服处理'];
            }
            return json_encode($result);

        }else{
            $result = ["result"=>0,'data'=>"支付出错,订单状态：".$res['trade_state']];
            return json_encode($result);
        }
    }


    public function wxpay($body){
        ksort($body);
        $xml="<xml>";
        $sign="";
        foreach($body as $k=>$v){
            $xml.="<{$k}>{$v}</{$k}>";
            $sign.="{$k}={$v}&";
        }
        $sign .="key=".\Yii::$app->params['sh_key'];
        $sign=strtoupper(md5($sign));
        $xml.="<sign>{$sign}</sign></xml>";
        $url="https://api.mch.weixin.qq.com/pay/unifiedorder";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
        $res = curl_exec($ch);
        curl_close($ch);
        $res = simplexml_load_string($res,"SimpleXMLElement",LIBXML_NOCDATA);
        $res =  json_decode(json_encode($res),true);
        $return_arr=[
            "timeStamp"=>time(),
            "appId"=>\Yii::$app->params['appid'],
            "nonceStr"=>\Yii::$app->security->generateRandomString(),
            "package"=>"prepay_id=".$res['prepay_id'],
            "signType"=>"MD5",
        ];
        ksort($return_arr);
        $pay_sign="";
        foreach($return_arr as $k=>$v){
            $pay_sign.="{$k}={$v}&";
        }
        $pay_sign.="key=".\Yii::$app->params['sh_key'];
        $return_arr['pay_sign'] = strtoupper(md5($pay_sign));
        return $return_arr;
    }



    public function change_pay_info($id_arr=[],$num_arr=[],$type=0){
            //更新限时购
            $id = json_decode($id_arr,true);
            $num = json_decode($num_arr,true);
            if(count($id)>0){
                foreach($id as $k=>$v){
                    $hd_model = NewuserRecorder::find()->where('user_id='.$this->user->id)->andWhere('hd_id='.$v)->andWhere('hd_type='.$type)->one();
                    if(!$hd_model){
                        $hd_model  =new NewuserRecorder();
                        $hd_model->hd_type=$type;
                        $hd_model->hd_id = $v;
                        $hd_model->user_id = $this->user->id;
                        $hd_model->addtime = time();
                    }
                    $hd_model->num = $num[$k];
                    $hd_model->updatetime = time();
                    $hd_model->save(false);
                }

            }
    }
    

    public function goods_num_reduce($attr_str=""){
        if(empty($attr_str)){
            return;
        }
        $attr = json_decode($attr_str,true);
        foreach($attr as $v){
            $model = GoodsRecorder::find()->where('id=:id',[':id' => $v['id']])->one();
            if(empty($model)){
                continue;
            }
            $goods_num = $model->goods_num-$v['num'];
            $model->goods_num = ($goods_num<0)?0:$goods_num;
            if($v['attr_id']>=0){//属性商品减库存
                $specs_value = json_decode($model->specs_value,true);
                if(!is_array($specs_value)){
                    continue;
                }
                $goods = $specs_value[$v['attr_id']];
                $goods['num'] = ($goods['num']-$v['num'])<0?0:$goods['num']-$v['num'];
                $specs_value[$v['attr_id']]=$goods;
                $model->specs_value=json_encode($specs_value);
            }
            $model->sell_num += $v['num'];//出售数量
            $model->save(false);
        }
    }



    public function actionYhq(){
        $post = \Yii::$app->request->post('page');
        $page = intval($post['page'])-1;
        $pagesize = \Yii::$app->params['pagesize'];
        $offset = $page*$pagesize;
        $list = CouponuserRecorder::find();
        $list = $list->limit($pagesize)->offset($offset)->where('user_id='.$this->user->id)->andWhere('is_use=0')->andWhere('is_del=0')->asArray()->all();
        $arr=[];
        foreach($list as $k=>$v){

            $coupon = CouponRecorder::find()->where('id='.$v['coupon_id'])->one();
            if(empty($coupon)){
                $arr[$k]['reduce'] = 0;
                $arr[$k]['name'] = "优惠券不存在，请删除";
                $arr[$k]['count'] = 0;
            }else{
                $arr[$k]['reduce'] = $coupon->reduce;
                $arr[$k]['count'] = $coupon->count;
                $arr[$k]['name'] = "消费".$coupon->count."元抵扣".$coupon->reduce."元";
            }
            $arr[$k]['day'] = $coupon->day;
            $time = strtotime("+ ".$coupon->day." days",$v['addtime']);
            $arr[$k]['day_time'] = date('Y-m-d H:i:s',$time);
            $arr[$k]['is_time'] = 0;
            if($time<=time()){
                $arr[$k]['is_time'] = 1;//过期
            }
            $arr[$k]['is_use'] = $v['is_use'];
            $arr[$k]['id'] = $v['id'];

        }
        if($arr){
            $result = ['result'=>1,'data'=>$arr];
        }else{
            $result = ['result'=>0];
        }
        return json_encode($result,JSON_NUMERIC_CHECK);
    }


    public function actionGetyhq(){
        $id = \Yii::$app->request->post('id');
        $model = CouponuserRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(empty($model)){
            $result = ['result'=>0,'data'=>'没有优惠券信息，可能活动已经结束，无法查看'];
            return json_encode($result);
        }
        $coupon_model = CouponRecorder::find()->where('id='.$model->coupon_id)->one();
        if(empty($coupon_model)){
            $result = ['result'=>0,'data'=>'没有优惠券信息，可能活动已经结束，无法查看'];
            return json_encode($result);
        }
        $info = "满".$coupon_model->count."元减".$coupon_model->reduce."元";
        $result = ['result'=>1,'data'=>$info];
        return json_encode($result);
    }

}
